#!/usr/bin/env node

const { execSync } = require('child_process');
const fs = require('fs');
const path = require('path');

console.log('🚀 预发布检查...\n');

// 检查必要的文件
const requiredFiles = [
  'package.json',
  'README.md', 
  'LICENSE',
  'src/index.js',
  'src/generator.js',
  'src/cli.js'
];

console.log('1. 检查必要文件...');
requiredFiles.forEach(file => {
  if (fs.existsSync(file)) {
    console.log(`✅ ${file}`);
  } else {
    console.log(`❌ ${file} - 文件缺失`);
    process.exit(1);
  }
});

// 检查 package.json 字段
console.log('\n2. 检查 package.json...');
const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));
const requiredFields = ['name', 'version', 'description', 'main', 'license'];
requiredFields.forEach(field => {
  if (pkg[field]) {
    console.log(`✅ ${field}: ${pkg[field]}`);
  } else {
    console.log(`❌ ${field} - 字段缺失`);
    process.exit(1);
  }
});

// 运行测试
console.log('\n3. 运行测试套件...');
try {
  execSync('npm test', { stdio: 'inherit' });
  console.log('✅ 测试通过');
} catch (error) {
  console.log('❌ 测试失败');
  process.exit(1);
}

// 打包测试
console.log('\n4. 打包测试...');
try {
  execSync('npm pack', { stdio: 'inherit' });
  const tarball = `${pkg.name}-${pkg.version}.tgz`;
  if (fs.existsSync(tarball)) {
    console.log(`✅ 打包成功: ${tarball}`);
    // 清理
    fs.unlinkSync(tarball);
  }
} catch (error) {
  console.log('❌ 打包失败');
  process.exit(1);
}

console.log('\n🎉 预发布检查完成！可以安全发布。');